package com.app.config;

import com.app.utils.CacheUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 默认情况下的模板只能支持RedisTemplate<String, String>，也就是只能存入字符串，这在开发中是不友好的，
 * 所以自定义模板是很有必要的.
 * 其中@Configuration 代表这个类是一个配置类，然后@AutoConfigureAfter(RedisAutoConfiguration.class)
 * 是让我们这个配置类在内置的配置类之后在配置，
 * 这样就保证我们的配置类生效，并且不会被覆盖配置。其中需要注意的就是方法名一定要叫redisTemplate
 * 因为@Bean注解是根据方法名配置这个bean的name的。
 * <p>
 *
 * @autor xiaoyu.fang
 * @date 2019/4/25 11:12
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    /**
     * 配置自定义redisTemplate
     *
     * @return
     */
    @Bean
    RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 注入封装RedisTemplate
     *
     * @param redisTemplate
     * @return
     */
    @Bean(name = "cacheUtil")
    public CacheUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
        CacheUtil redisUtil = new CacheUtil();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }
}
